package com.mxm.mirai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mxm.mirai.config.MXM_config;
import com.mxm.mirai.dao.Botgroups;
import com.mxm.mirai.dao.Weibor;
import com.mxm.mirai.mapper.WeiborMapper;
import com.mxm.mirai.service.WeiborService;
import net.dreamlu.mica.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 漫小猫
 * @since 2020-09-24
 */
@Service
public class WeiborServiceImpl extends ServiceImpl<WeiborMapper, Weibor> implements WeiborService {

    @Autowired
    WeiborMapper weiborMapper;
    private Weibor weibor = null;

    @Override
    public boolean getWeiborByTitle(String title) {
        if (0<weiborMapper.selectCount(new QueryWrapper<Weibor>().eq("title",title))){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean InsertWeibor(String title) {
        try {
            weibor = new Weibor();
            weibor.setTitle(title);
            weiborMapper.insert(weibor);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    @Override
    public String getWeibo(){
        String html = HttpRequest.get("https://s.weibo.com/top/summary?cate=realtimehot").addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36")
                .connectTimeout(Duration.ofSeconds(40))
                .execute().asString();
        String data="",url,title,index,state=null;
        Matcher m = Pattern.compile("<tr([\\s\\S]*?)<a href=\"(.*?)\"(.*?)>(.*?)</a>([\\s\\S]*?)<span>(.*?)</span>([\\s\\S]*?)td-03\">(.*?)</td>([\\s\\S]*?)</tr>").matcher(html);
        while (m.find()) {
            url = "https://s.weibo.com"+m.group(2);
            title = m.group(4);
            index = m.group(6);
            state = Matcher(m.group(8));
            state = state==null?"":"["+state+"]";
            if(!getWeiborByTitle(title)){
                InsertWeibor(title);
                data += title+" "+index+" "+state+"\n"+ MXM_config.bottools.DwzUrl(url)+"\n------------\n";
            }
        }
        return data;
    }

    public static String Matcher(String msg){
        //System.out.println(msg);
        Matcher m = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(msg);
        while (m.find()) {
            return m.group();
        }
        return null;
    }
}
